package com.apkicon.parser;

import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Android资源解析器
 * 按照Android原生密度优先级查找图标资源
 */
public class AndroidResourceResolver {
    
    /**
     * Android密度优先级（从高到低）
     * 按照Android系统选择资源的优先级
     */
    private static final String[] DENSITY_PRIORITY = {
        "xxxhdpi", "xxhdpi", "xhdpi", "hdpi", "mdpi", "ldpi"
    };
    
    /**
     * 根据AndroidManifest.xml中的图标引用查找最佳资源
     */
    public static IconResource findBestIconResource(ZipFile apkFile, AndroidManifestParser.AppIconInfo appIconInfo) {
        String resourceName = appIconInfo.getResourceName();
        String resourceType = appIconInfo.getResourceType();
        
        System.out.println("🔍 查找资源: " + resourceName + " (类型: " + resourceType + ")");
        
        // 1. 优先查找Adaptive Icon
        if (appIconInfo.hasAdaptiveIcon()) {
            IconResource adaptiveIcon = findAdaptiveIconResource(apkFile, resourceName);
            if (adaptiveIcon != null) {
                System.out.println("✅ 找到Adaptive Icon: " + adaptiveIcon.getPath());
                return adaptiveIcon;
            }
        }
        
        // 2. 按密度优先级查找PNG/WebP图标
        IconResource bestIcon = findIconByDensityPriority(apkFile, resourceName, resourceType);
        if (bestIcon != null) {
            System.out.println("✅ 找到最佳图标: " + bestIcon.getPath() + 
                             " (密度: " + bestIcon.getDensity() + ", 尺寸: " + bestIcon.getSize() + ")");
            return bestIcon;
        }
        
        // 3. 查找Vector Drawable
        IconResource vectorIcon = findVectorDrawable(apkFile, resourceName, resourceType);
        if (vectorIcon != null) {
            System.out.println("✅ 找到Vector Drawable: " + vectorIcon.getPath());
            return vectorIcon;
        }
        
        // 4. 如果没找到指定资源，尝试智能搜索其他可能的图标
        System.out.println("⚠️ 未找到指定资源，尝试智能搜索...");
        IconResource smartIcon = findIconBySmartSearch(apkFile);
        if (smartIcon != null) {
            System.out.println("✅ 智能搜索找到图标: " + smartIcon.getPath());
            return smartIcon;
        }
        
        System.out.println("❌ 未找到任何图标资源");
        return null;
    }
    
    /**
     * 查找Adaptive Icon资源
     */
    private static IconResource findAdaptiveIconResource(ZipFile apkFile, String resourceName) {
        // Adaptive Icon通常位于mipmap目录
        String[] searchPaths = {
            "res/mipmap-anydpi-v26/" + resourceName + ".xml",
            "res/mipmap-anydpi/" + resourceName + ".xml"
        };
        
        for (String path : searchPaths) {
            ZipEntry entry = apkFile.getEntry(path);
            if (entry != null) {
                return new IconResource(path, "adaptive", 108, "anydpi");
            }
        }
        
        return null;
    }
    
    /**
     * 按Android PackageManager算法查找图标
     */
    private static IconResource findIconByDensityPriority(ZipFile apkFile, String resourceName, String resourceType) {
        // 使用Android密度解析器，目标DPI为320（xhdpi，最常用的密度）
        int targetDpi = 320; // xhdpi
        IconResource bestMatch = AndroidDensityResolver.findBestDensityMatch(apkFile, resourceName, resourceType, targetDpi);
        
        if (bestMatch != null) {
            return bestMatch;
        }
        
        // 如果没找到，尝试其他常见密度
        int[] commonDpis = {480, 240, 160, 640}; // xxhdpi, hdpi, mdpi, xxxhdpi
        for (int dpi : commonDpis) {
            bestMatch = AndroidDensityResolver.findBestDensityMatch(apkFile, resourceName, resourceType, dpi);
            if (bestMatch != null) {
                System.out.println("✅ 使用备选密度DPI: " + dpi);
                return bestMatch;
            }
        }
        
        return null;
    }
    
    /**
     * 查找Vector Drawable - 按照Android PackageManager方式
     */
    private static IconResource findVectorDrawable(ZipFile apkFile, String resourceName, String resourceType) {
        // 按照Android密度优先级查找Vector Drawable
        for (String density : DENSITY_PRIORITY) {
            String xmlPath = "res/" + resourceType + "-" + density + "/" + resourceName + ".xml";
            ZipEntry entry = apkFile.getEntry(xmlPath);
            if (entry != null) {
                // 验证是否为Vector Drawable
                byte[] xmlData = AndroidXmlIconParser.readXmlFromApk(apkFile, xmlPath);
                if (xmlData != null && AndroidXmlIconParser.isVectorDrawable(xmlData)) {
                    AndroidXmlIconParser.XmlIconInfo xmlInfo = AndroidXmlIconParser.parseXmlIcon(xmlData);
                    if (xmlInfo != null) {
                        int size = getSizeForDensity(density);
                        return new IconResource(xmlPath, "xml", size, density);
                    }
                }
            }
        }
        
        // 查找无密度标识的Vector Drawable
        String[] searchPaths = {
            "res/" + resourceType + "/" + resourceName + ".xml",
            "res/drawable-anydpi-v21/" + resourceName + ".xml",
            "res/drawable-anydpi/" + resourceName + ".xml"
        };
        
        for (String path : searchPaths) {
            ZipEntry entry = apkFile.getEntry(path);
            if (entry != null) {
                // 验证是否为Vector Drawable
                byte[] xmlData = AndroidXmlIconParser.readXmlFromApk(apkFile, path);
                if (xmlData != null && AndroidXmlIconParser.isVectorDrawable(xmlData)) {
                    AndroidXmlIconParser.XmlIconInfo xmlInfo = AndroidXmlIconParser.parseXmlIcon(xmlData);
                    if (xmlInfo != null) {
                        return new IconResource(path, "xml", xmlInfo.getWidth(), "anydpi");
                    }
                }
            }
        }
        
        return null;
    }
    
    /**
     * 根据密度获取对应的图标尺寸
     */
    private static int getSizeForDensity(String density) {
        switch (density) {
            case "ldpi": return 36;
            case "mdpi": return 48;
            case "hdpi": return 72;
            case "xhdpi": return 96;
            case "xxhdpi": return 144;
            case "xxxhdpi": return 192;
            default: return 48;
        }
    }
    
    /**
     * 智能搜索图标（当指定资源不存在时）
     */
    private static IconResource findIconBySmartSearch(ZipFile apkFile) {
        // 常见的应用图标命名模式
        String[] commonIconNames = {
            "ic_launcher", "launcher", "app_icon", "icon", "logo", "ic_app"
        };
        
        // 使用Android密度算法搜索mipmap目录
        for (String iconName : commonIconNames) {
            IconResource bestMatch = AndroidDensityResolver.findBestDensityMatch(apkFile, iconName, "mipmap", 320);
            if (bestMatch != null) {
                System.out.println("✅ 智能搜索找到mipmap图标: " + bestMatch.getPath());
                return bestMatch;
            }
        }
        
        // 使用Android密度算法搜索drawable目录
        for (String iconName : commonIconNames) {
            IconResource bestMatch = AndroidDensityResolver.findBestDensityMatch(apkFile, iconName, "drawable", 320);
            if (bestMatch != null) {
                System.out.println("✅ 智能搜索找到drawable图标: " + bestMatch.getPath());
                return bestMatch;
            }
        }
        
        // 最后尝试查找任何PNG文件（作为最后的fallback）
        // 优先选择mipmap目录中的PNG文件
        IconResource mipmapIcon = apkFile.stream()
            .filter(entry -> entry.getName().startsWith("res/") && 
                           entry.getName().endsWith(".png") &&
                           entry.getName().contains("mipmap"))
            .findFirst()
            .map(entry -> {
                String path = entry.getName();
                String density = extractDensityFromPath(path);
                int size = getSizeForDensity(density);
                return new IconResource(path, "png", size, density);
            })
            .orElse(null);
            
        if (mipmapIcon != null) {
            return mipmapIcon;
        }
        
        // 如果mipmap中没有，查找drawable目录
        IconResource drawableIcon = apkFile.stream()
            .filter(entry -> entry.getName().startsWith("res/") && 
                           entry.getName().endsWith(".png") &&
                           entry.getName().contains("drawable"))
            .findFirst()
            .map(entry -> {
                String path = entry.getName();
                String density = extractDensityFromPath(path);
                int size = getSizeForDensity(density);
                return new IconResource(path, "png", size, density);
            })
            .orElse(null);
            
        if (drawableIcon != null) {
            return drawableIcon;
        }
        
        // 最后尝试查找任何PNG文件（处理资源混淆的情况）
        return apkFile.stream()
            .filter(entry -> entry.getName().startsWith("res/") && 
                           entry.getName().endsWith(".png"))
            .findFirst()
            .map(entry -> {
                String path = entry.getName();
                String density = extractDensityFromPath(path);
                int size = getSizeForDensity(density);
                return new IconResource(path, "png", size, density);
            })
            .orElse(null);
    }
    
    /**
     * 从路径中提取密度信息
     */
    private static String extractDensityFromPath(String path) {
        for (String density : DENSITY_PRIORITY) {
            if (path.contains("-" + density + "/")) {
                return density;
            }
        }
        return "mdpi"; // 默认密度
    }
    
    /**
     * 获取密度评分（用于排序）
     */
    public static int getDensityScore(String density) {
        for (int i = 0; i < DENSITY_PRIORITY.length; i++) {
            if (DENSITY_PRIORITY[i].equals(density)) {
                return DENSITY_PRIORITY.length - i; // 高密度得分高
            }
        }
        return 0;
    }
}
